#pragma once
#include "WarningStrategyChain.h"
#include "MediawikiXmlReader.h"

class CAivReportWarning :
	public CWarningStrategyChain
{
protected:
	QString GetWarningContents(QString pageName) const { throw "Invalid operation"; };
	QString GetSummary(QString pageName) const { throw "Invalid operation"; };
	QString GetOverridingLevels() const { return ""; /* nothing overrides an AIV report */ };
public:

	CAivReportWarning(void):CWarningStrategyChain(NULL)
	{
	}

	virtual bool IssueWarning(QString user, QString page, QString pageName) const
	{
		static QRegExp ipAddrRegex("\\d+\\.\\d+\\.\\d+\\.\\d+");
		// Load AIV
		QString url("http://en.wikipedia.org/w/api.php?titles=Wikipedia:Administrator%20intervention%20against%20vandalism"
			"&action=query&prop=revisions&export=1&exportnowrap=1&");
		QUrl uri(url);
		QNetworkRequest request = CollabRC::CreateNetworkRequest(uri);
		QNetworkAccessManager &manager = CollabRC::GetNetworkManager();
		QNetworkReply *reply = manager.get(request);

		// Wait for response
		QEventLoop loop;
		loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
		loop.exec();

		// Read current contents
		CMediawikiXmlReader handler(NULL);
		QXmlSimpleReader reader;
		reader.setContentHandler(&handler);
		reader.parse(QXmlInputSource(reply));

		delete reply;
		if (!handler.errorOccurred())
		{
			// Append to the contents
			QString text = handler.GetText();
			if (ipAddrRegex.exactMatch(user))
				text += "\n*{{IPVandal|";
			else
				text += "\n*{{Vandal|";
			
			text += user;
			// TODO: Remove admin warning
			text += "}} Vandalism after final warning. <small>'''Administrators please note:''' This report is generated from a tool that is currently in testing. Please be sure to pay close attention to edits before acting.</small> --~~~~";
			

			// Get edit token
			// TODO: I18N Site
			url = "http://en.wikipedia.org/w/api.php?action=query&prop=info&intoken=edit&titles=Wikipedia:Administrator%20intervention%20against%20vandalism&format=xml";
			uri = QUrl(url);

			QNetworkRequest tokenRequest = CollabRC::CreateNetworkRequest(uri);
			reply = manager.get(tokenRequest);

			// wait for download to complete
			loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
			loop.exec();

			QXmlSimpleReader tokenReader;
			tokenReader.setContentHandler(&handler);
			tokenReader.parse(QXmlInputSource(reply));

			delete reply;
			if (!handler.errorOccurred())
			{
				// Ok got the token, so do the edit
				// TODO: I18N site
				url = "http://en.wikipedia.org/w/api.php?action=edit&format=xml&title=Wikipedia:Administrator%20intervention%20against%20vandalism";
				uri = QUrl(url);
				QNetworkRequest editRequest = CollabRC::CreateNetworkRequest(uri);

				QString postData = "text=" + QUrl::toPercentEncoding(text) + "&token=" + QUrl::toPercentEncoding(handler.GetEditToken()) +
					"&summary=" + QUrl::toPercentEncoding("Reporting [[Special:Contributions/" + user + "|" + user + "]] " + CollabRC::GetSummaryTag());
				reply = manager.post(editRequest, postData.toAscii());

				// Wait for response
				loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
				loop.exec();

				// TODO: Check for error
				delete reply;
				return true;
			}

		}
		
		// TODO: Handle error gracefully
		return false;
	}

	virtual ~CAivReportWarning(void)
	{
	}
};
